package gupao.concurrency.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockSample {

    static class LocalCache{
        static Map<String, Object> map = new HashMap<>();
        static ReadWriteLock rwl = new ReentrantReadWriteLock();
        static Lock readLock = rwl.readLock();
        static Lock writeLock = rwl.writeLock();

        public static Object get(String key){
            readLock.lock();
            try{
                return map.get(key);
            }finally {
                readLock.unlock();
            }
        }

        public static void put(String key, Object val){
            writeLock.lock();
            try{
                map.put(key, val);
            }finally {
                writeLock.unlock();
            }
        }

        public static void delete(String key){
            writeLock.lock();
            try{
                map.remove(key);
            }finally {
                writeLock.unlock();
            }
        }
    }
}
